<?php

class BbData {

	public function save($userId, $userName = '', $data) {

		if ($userId == null || $userId == '' || $data == null || $data == '') return false;
		
		$commonDao = Vega_Dao::factory('Bbservice_Common');
		
		$prevUserName = $commonDao->getUserName($userId);
		
		if ($prevUserName == null) 
			$commonDao->addUser($userId, $userName);
		else if ($userName != '' && $userName != $prevUserName) {
			//update new user's name
			$commonDao->updateUserName($userId, $userName);		
		}
		
		$data = json_decode($data);
		
		if (isset($data->reqs) && is_array($data->reqs)) {
			$data = $data->reqs[0];
			
			if (isset($data->plantData)) {	//init data
				
				$commonDao->addPlantsByArray($data->plantData);
				$commonDao->addUsersByArray(array($data->currentUser));
				$commonDao->addUsersByArray($data->friends);
				$this->addFields($userId, $data->farm->fields);
				
				$commonDao->recalculateHarvertTime();
				return true;
			}
			else if (isset($data->items)) {	//get event data
				return true;
			}
			else if (isset($data->fields)) {	//get farm data
				$this->addFields($userId, $data->fields);
				$commonDao->recalculateHarvertTime();
				return true;
			}
			else { //unknown data
				return false;
			}
		
		}
		else { //unknown data
			return false;
		}
		
	}
	

	private function addFields($userId, $fields) {
		
		$commonDao = Vega_Dao::factory('Bbservice_Common');
	
		$squareList = array();
		$squareListStr = '-1';
		$eventList = array();
		foreach ($fields as $f) {
			$remainUnit = isset($f->nU)?$f->nU:65535;
			if (isset($f->plantId)) {
				$squareList[] = array(
					'square_id' => $f->squareId,
					'user_id' => $userId,
					'plant_id' => $f->plantId,
					'plant_time' => $f->plantTime,
					'gen' => $f->gen,
					'last_harvert_time' => $f->phTime,
					'is_fertilised' => $f->isFertilised,
					'remain_unit' => $remainUnit,
					);
					
				$squareListStr .= ','.$f->squareId;
				
				foreach ($f->events as $e) {
					$eventList[] = array(
						'farm_id' => $f->squareId,
						'type_id' => $e[0],
						'time' => $e[1],
						'param' => isset($e[2])?$e[2]:0);
				}
			}
		}				
		
		$commonDao->removeFarms($userId);
		$commonDao->removeFarmEvents($squareListStr);

		$commonDao->addFarmsByArray($squareList);
		$commonDao->addEventsByArray($eventList);
	}	
	
}